<?php
/**
 * @version 	$Id: fDB.class.php 74 2010-03-17 06:48:21Z mylifeisskidrow@gmail.com $
 * @author 		$Author: mylifeisskidrow@gmail.com $
 * @copyright 	Copyright (c) 2010 Luu Trong Hieu. All right reserved.
 * @license 	GNU/GPL see license.php
 */

defined('IN_FLYWHEEL') or die('Restricted Access');

/**
 * Database
 * 
 * @abstract 
 * @package 	system
 * @subpackage 	databases
 *
 */
abstract class fDatabase {
	private static $config = array();
	protected static $connections;
	
	/**
	 * Init Config
	 *
	 */		
	private static function initConfig() {
		self::$config = include (_PROJECT_CONFIGURATION_PATH_.'database.config.php');		
	}
    
    public static function profiler() {
        $newlineSQLKeywords = '/<strong>'
				.'(FROM|LEFT|INNER|OUTER|WHERE|SET|VALUES|ORDER|GROUP|HAVING|LIMIT|ON|AND|OR)'
				.'<\\/strong>/i';
		$sqlKeyword = array (
			'ASC', 'AS',  'ALTER', 'AND', 'AGAINST',
			'BETWEEN', 'BOOLEAN', 'BY',
			'COUNT',
			'DESC',  'DISTINCT', 'DELETE',
			'EXPLAIN',
			'FOR', 'FROM',
			'GROUP',
			'HAVING',
			'INSERT', 'INNER', 'INTO', 'IN',
			'JOIN',
			'LIKE', 'LIMIT', 'LEFT',
			'MATCH', 'MODE',
			'NOT',
			'ORDER', 'OR', 'OUTER', 'ON',
			'REPLACE', 'RIGHT',
			'STRAIGHT_JOIN', 'SELECT', 'SET',
			'TO', 'TRUNCATE',
			'UPDATE',
			'VALUES',
			'WHERE',);

		$sqlReplaceKeyword = array (
			'<strong>ASC</strong>', '<strong>AS</strong>',  '<strong>ALTER</strong>', '<strong>AND</strong>', '<strong>AGAINST</strong>',
			'<strong>BETWEEN</strong>', '<strong>BOOLEAN</strong>', '<strong>BY</strong>',
			'<strong>COUNT</strong>',
			'<strong>DESC</strong>',  '<strong>DISTINCT</strong>', '<strong>DELETE</strong><br />',
			'<strong>EXPLAIN</strong>',
			'<strong>FOR</strong>', '<strong>FROM</strong>',
			'<strong>GROUP</strong>',
			'<strong>HAVING</strong>',
			'<strong>INSERT</strong>', '<strong>INNER</strong>', '<strong>INTO</strong>', '<strong>IN</strong>',
			'<strong>JOIN</strong>',
			'<strong>LIKE</strong>', '<strong>LIMIT</strong>', '<strong>LEFT</strong>',
			'<strong>MATCH</strong>', '<strong>MODE</strong>',
			'<strong>NOT</strong>',
			'<strong>ORDER</strong>', '<strong>OR</strong>', '<strong>OUTER</strong>', '<strong>ON</strong>',
			'<strong>REPLACE</strong><br />', '<strong>RIGHT</strong>',
			'<strong>STRAIGHT_JOIN</strong>', '<strong>SELECT</strong><br />', '<strong>SET</strong>',
			'<strong>TO</strong>', '<strong>TRUNCATE</strong><br />',
			'<strong>UPDATE</strong><br />',
			'<strong>VALUES</strong>',
			'<strong>WHERE</strong>');
        
        $time = 0;
        $queriesLogNo = 0;
        echo '<div id="sql-report"><h4>Queries Logged</h4><ol>';
        foreach(self::$connections as $conn) {
            $profiler = $conn->getListener();
            foreach($profiler as $event) {
                $time += $event->getElapsedSecs();                
                $sql = str_replace($sqlKeyword, $sqlReplaceKeyword, $event->getQuery());
                if ($sql != null) {
                    ++$queriesLogNo;
                }
				$sql = preg_replace('/\"([^\"])+\"/','<font color="#ff000;">\\0</font>', $sql);
				$sql = preg_replace('/\'([^\'])+\'/','<font color="#ff000;">\\0</font>', $sql);
				$sql = preg_replace($newlineSQLKeywords, '<br />&nbsp;&nbsp;\\0', $sql);
                echo '<li><i>' .$event->getName() .'</i> : ' .$sql .'<br /><em>'
                           . sprintf("%f", $event->getElapsedSecs()) .'</em>';
                
                echo '</li>';
            }
        }
        
        echo '</ol><br />Total <strong>' . $queriesLogNo . '</strong>
            SQL queries logged take <em>'. $time .'</em> seconds exec';
    }

	/**
	 * Get Database
	 *
	 * @param string $name
	 * @return fMySQL
	 */
	public static function getConnection($name = null) {
		if (sizeof(self::$config) === 0) {
			self::initConfig();		
		}
		
		if ($name === null || !isset(self::$config['database'][$name])) {
			// Neu khong chi dinh ro ten hoac ten khong nam trong config thi se load ra doi tuong default
			$name = self::getDefault();			
		}
		
		if (!isset(self::$config['database'][$name])) {// Neu khong co config nao co ten nhu vay
			throw new fDatabaseException('Config "' .$name .'" not found!');			
		}
		
		if (!isset(self::$connections[$name])) {                        
			self::$connections[$name] = Doctrine_Manager::connection(self::$config['database'][$name], $name);            
            if (fConfig::get('debug')) {
                $profiler = new Doctrine_Connection_Profiler();
                self::$connections[$name]->setListener($profiler);
            }
		}
				
		return self::$connections[$name];
	}
	
	public static function getDefault() {
		return self::$config['default'];
	}
}